package com.util;

import java.io.File;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;


import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Clear;
import com.jfinal.kit.HttpKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;


/**
 * @author 作者 :wangyilong
 * @version 创建时间：2018年6月5日 
 * 类说明:ApplicationUtils : 程序工具类，提供大量的便捷方法
 */
public class ApplicationUtils {
	private  static long makeId = System.currentTimeMillis()*1000;

	 /**
	  * 生成4位随机数
	  * */
	 
	 public  static String  makeSmsRandom(){
		 int random  = (int) (Math.random()*9000+1000);
		 return  random +"";
	 }
	 /**
	  * 生成6位随机数
	  * */
	 public  static String  smsRandomNum(){
		Random random = new Random();

		int x = random.nextInt(899999);

		x = x+100000;
		return x+"";
	 }
	
    /**
     * 产生一个36个字符的UUID
     *
     * @return UUID
     */
    public static String randomUUID() {
        return UUID.randomUUID().toString();
    }


    /**
     * 
     * 判断是否为数字
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
    	if(str == null||str=="null"||str=="")  return false;
    	for (int i = 0; i < str.length(); i++){
		   if (!Character.isDigit(str.charAt(i))){
		    return false;
		   }
    	}
    	return true;
    }
    /**
     * Strng转Integer类型
     * @param num 
     * @return
     */
    public static Integer stringSwitchInteger(String num){
    	if(isNumeric(num)){
    		return new Integer(num);
    	}else{
    		return 0;
    	}
    }
    
    /**
     * Strng转Double类型
     * @param str
     * @return
     */
    public static Double stringSwitchDouble(String str) {
    	Double num=0.0;
    	if(str == null||str=="null"||str=="")  return num;
    	for (int i = 0; i < str.length(); i++){
		   if (!Character.isDigit(str.charAt(i))&&str.charAt(i)!='.'){
			   num=Double.parseDouble(str.substring(0, i));
			   break;
		   }
		   if(i==str.length()-1){
			   num=Double.parseDouble(str);
		   }
    	}
    	return num;
    }
    
    /**
     * 字符串转double转BigDecimal
     * @param str
     * @return
     */
    public static BigDecimal stringSwitchBigDecimal(String str) {
    	Double num=0.0;
    	if(str == null||str=="null"||str=="") return new BigDecimal(num);
    	for (int i = 0; i < str.length(); i++){
		   if (!Character.isDigit(str.charAt(i))&&str.charAt(i)!='.'){
			   num=Double.parseDouble(str.substring(0, i));
			   break;
		   }
		   if(i==str.length()-1){
			   num=Double.parseDouble(str);
		   }
    	}
    	return new BigDecimal(num);
    }
    /**
     * double保留两位小数
     * DecimalFormat转换最简便
     */
	public static String format (double f) {
		if(f==0)return "0";
		DecimalFormat df = new DecimalFormat("#.00");
		System.out.println(df.format(f));
		return df.format(f);
	}

    /**
	 * 如果是关联查询的方式，将查询条件转换一下（“_”转换成“.”）
	 **/
     public static String conditions(String conditions) {
        if (conditions!=null&&conditions!=""&&conditions.indexOf("_")!=-1) {
        	return conditions.replace("_", ".");
        }else{
        	return conditions; 
        } 
     }
    
	/**
	 * 产生一个Id生产方法/
	 * */
     public static String makeId() {  
        if (makeId/1000 < System.currentTimeMillis() | makeId/1000 >System.currentTimeMillis()) {
        	makeId = System.currentTimeMillis()*1000;
        	return String.valueOf(makeId);
        }else{
        	return String.valueOf(++makeId); 
        } 
     }  
     
     public static String getRealIp(HttpServletRequest request) {
 		String ip = request.getHeader("x-forwarded-for");
 		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
 			ip = request.getHeader("Proxy-Client-IP");
 		}
 		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
 			ip = request.getHeader("WL-Proxy-Client-IP");
 		}
 		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
 			ip = request.getRemoteAddr();
 		}
 		return ip.split(",")[0];
 	}
     /**
      * 返回项目时间表里面的年份
      */
     public static String getPrjYear(){
    	Record record = Db.findFirst("select distinct year from dl_prjtime");
		return record.getStr("year");
     }
     
     /**
      * 返回当前时间
      */
     public static String getTime(){
    	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式 HH:mm:ss
		return df.format(new Date());
     }
     
     /**
      * 返回当前时间
      */
     public static Date getDateTime(){
    	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		try {
			return df.parse(df.format(new Date()));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
     }
     /**
      * 返回当前时间
      */
     public static String DateTime(){
    	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		return df.format(new Date());
     }
     /**
      * 判断是否在对应的时间范围内
      * type 时间段 1上午场8-12，2下午场1-5
      */
     public static boolean ckDateTime(String type){
    	 Integer i =stringSwitchInteger(type);
    	String [] be={"08:00","13:00"};
    	String [] en={"12:00","17:00"};
    	SimpleDateFormat df = new SimpleDateFormat("HH:mm");// 设置日期格式
 		Date nowTime = null;
 		Date beginTime = null;
 		Date endTime = null;
 		try {
 			nowTime = df.parse(df.format(new Date()));
 			beginTime = df.parse(be[i-1]);
 			endTime = df.parse(en[i-1]);
 		} catch (Exception e) {
 			e.printStackTrace();
 		}
 		Calendar date = Calendar.getInstance();
 		date.setTime(nowTime);

 		Calendar begin = Calendar.getInstance();
 		begin.setTime(beginTime);

 		Calendar end = Calendar.getInstance();
 		end.setTime(endTime);

 		if (date.after(begin) && date.before(end)) {
 			return true;
 		} else {
 			return false;
 		}
     }

    /**
     * 字符串切割成数组
     * @param str 要切割的字符串
     * @param type 切割参数
     * @return
     */
    public static String [] stringSwitchNumerical(String str,String type){
    	String [] string=null;
    	if(str!=null){
    		if(str.indexOf(type)!=-1){
        		string=str.split(type);
    		}else{
    			string =new String[1];
    			string[0]=str;
    		}
    	}else{
    		string =new String[1];
			string[0]="0";
    	}
    	return string;
    }
    
    /**
     * 将传入的字符串去除空白的内容
     * @param str 要切割的字符串
     * @param type 切割参数
     * @return
     */
    public static String checkString(String string){
    	if(string==null)string="0";
    	string = string.replace(" ", "");
    	if(string.indexOf(",")!=-1){
    		String [] str = string.split(",");
    		String param="";
    		for (String s : str) {
    			System.out.println();
    			if(s!=null&&!s.equals("")&&s.indexOf(" ")==-1)param+=s+",";
    		}
    		return param.substring(0,param.length()-1);
    	}else{
    		return string;
    	}
    }
	/**
	 * 删除文件到方法（图片，视频）
	 */
 	public static boolean deleteFile(String photo) {
 		boolean falg = true;
 		if (photo != null) {
 			//进行查找本项目所在路径
 			File f = new File("ROOT");
 			String path = f.getAbsolutePath();
 			//找到路径进行替换拼接到图片路径
 			path=path.replace("\\", "/");
 			path=path.replace("bin", "webapps");
 			//获取该项目对象
 			String path1=path+photo;
 			File file = new File(path1);
 			if(file.exists()){
 				falg=file.delete();
 			}
 		}
 		return falg;
 	}
 	public static int begin(String str){
 		int begin;
		if (str == null || str=="") {
			begin = 1;
		}else{
			if(ApplicationUtils.isNumeric(str)){
				begin = Integer.parseInt(str);
			}else{
				begin = 1;
			}
		}
		return begin;
 	}
 // 获取 access_token 的接口地址（GET） 限 200（次/天）
 	public static String access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx7a5088333e7a7234&secret=e872122e41c93a40cc2512b4d542c3d4&code=CODE&grant_type=authorization_code";
 	
 	/**
	 * 获取 access_token
	 * @return
	 */
 	public static String getOpenid(String CODE) {
		String requestUrl = access_token_url.replace("CODE", CODE);
		System.out.println(requestUrl);
		String str = HttpKit.get(requestUrl);
		String str1=str.replace("{", "").replace("}", "").replace("\"", "");
		String [] string=str1.split(",");
		String openid=null;
		for (String s : string) {
			if(s.indexOf("openid")!=-1){
				openid = s.split(":")[1];
			}
		}
		return openid;
	}
 	
 	/**
 	 * json字符串转换成map
 	 * @return
 	 */
 	public static Map<String, Object> getMap(String str,String key) {
		String str1=str.replace("{", "").replace("}", "").replace("\"", "");
		String [] string=str1.split(",");
		Map<String, Object> map= new HashMap<String, Object>();
		for (String s : string) {
			map.put(s.split(":")[0], s.split(":")[1]);
		}
		return map;
	}
 	/**
 	 * json字符串获取指定的值
 	 * @param str
 	 * @param key 
 	 * @return
 	 */
 	public static String getJsonStr(String str,String key) {
 		String val="0";
		String str1=str.replace("{", "").replace("}", "").replace("\"", "");
		String [] string=str1.split(",");
		for (String s : string) {
			if(s.indexOf(key)!=-1){
				val=s.split(":")[1];
			}
		}
		return val;
	}
 	/**
 	 * 数组转字符串
 	 * @param str
 	 * @return
 	 */
 	public static String arraySwitchString(String[] str) {
 		String val="";
			for (int i = 0; i < str.length; i++) {
				if(str[i]!=null&&str[i]!="")
				val+=str[i]+(i<str.length-1?",":"");
			}
		return val;
	}
 	/**
 	 * 删除图片
 	 * @param path 图片路径
 	 * @param photo 图片名称
 	 */
 	public static boolean delImg(String path,String photo){
 		boolean falg=false;
 		String[] ph=photo.split(",");
		if(ph.length>0){
			for (int i = 0; i < ph.length; i++) {
				//和删除的路径不同，且不为空的时候赋值给str
				if(!ph[i].equals(photo)&&ph[i]!=""){
					String path1=path+ph[i];
					//建立路径，删除
					File file = new File(path1);
					falg=file.delete();
				}
			}
		}
		System.out.println(falg);
		return falg;
 	}
 	/**
 	 * 将头像或聊天文件替换成缩放路径
 	 */
 	public static String getMinimg(String url){
		if(url.indexOf("chat")!=-1){
			url=url.substring(0,21)+"min_"+url.substring(21,url.length());
		}else if(url.indexOf("picture")!=-1){
			url=url.substring(0,24)+"min_"+url.substring(24,url.length());
		}
		return url;
 	}
}
